package com.bocloud.kong.service.impl;

import static org.apache.commons.lang3.StringUtils.isBlank;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.bocloud.kong.client.ApiClient;
import com.bocloud.kong.model.Api;
import com.bocloud.kong.service.ApiService;
import com.bocloud.model.Result;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

/**
 * Title: ApiServiceImpl Description:
 *
 * @author lkx
 * @version 1.0.0
 * @since 2017-02-15 17:51
 */
@Service
public class ApiServiceImpl implements ApiService {

	private static Logger logger = LoggerFactory.getLogger(ApiServiceImpl.class);

	@Autowired
	private ApiClient client;

	@Override
	public Api query(String apiId) {
		try {
			Api api = client.queryOne(apiId);
			logger.debug("API的信息: {}", JSON.toJSONString(api));
			return api;
		} catch (IOException e) {
			logger.warn("{}", e);
		}
		return null;
	}

	@Override
	public Result save(Api api) {
		Preconditions.checkNotNull(api, "待保存的 API 信息不能为空");
		logger.info("待保存的 Api{}", api.toString());
		Api newApi;
		try {
			if (isBlank(api.getId()) && !existApi(api.getId())) {
				newApi = client.add(api);
			} else {
				newApi = client.update(api);
			}
			logger.info("保存后的 newApi{}", newApi.toString());
		} catch (IOException e) {
			logger.info("{}", e);
			return new Result(false, e.getMessage());
		}
		if (newApi != null && isBlank(newApi.getErrorMessage())) {
			return new Result(true, null, newApi);
		}
		return new Result(false, newApi == null ? "保存失败" : newApi.getErrorMessage());
	}

	@Override
	public List<Api> queryAll(Api api) {
		try {
			Api queryApi = api == null ? new Api() : api;
			queryApi.setSize(getApiAmount()+"");
			return client.query(queryApi);
		} catch (IOException e) {
			logger.info("{}", e);
		}
		return Lists.newArrayList(); // Never return null
	}

	@Override
	public void delete(String apiId) {
		try {
			client.delete(apiId);
		} catch (IOException e) {
			logger.info("{}", e);
		}
	}

	@Override
	public boolean isApiNameExist(String apiName) {
		Api api = query(apiName);
		return api != null && api.getId() != null;
	}

	/**
	 * 查询 Kong 上面的 API 数量, 如果查询失败或者没有 API, 则会返回 null.
	 *
	 * @return API 数量
	 */
	private Integer getApiAmount() {
		try {
			Api api = new Api();
			api.setSize(1+"");
			return client.totalSize(api);
		} catch (IOException e) {
			logger.info("{}", e);
		}
		return null;
	}

	/**
	 * 使用API id判断 Kong上面是否已经存在该API
	 *
	 * @return API 是否存在
	 */
	public boolean existApi(String apiId) {
		if (isBlank(apiId)) {
			return false;
		}
		try {
			Api api = client.queryOne(apiId);
			if (isBlank(api.getErrorMessage()) || isBlank(api.getId())) {
				return false;
			}
		} catch (IOException e) {
			logger.info("{}", e);
			return false;
		}
		return true;
	}
}
